// 文件名称：upload.js
// 完整保存路径：miniprogram/pages/upload/upload.js
// 功能说明：居家干预记录上传页逻辑控制
// 使用说明：处理居家干预记录创建、图片上传和表单提交

const { getToken } = require('../../utils/auth');

Page({
  data: {
    // 表单数据
    formData: {
      intervention_type: '',           // 干预方式
      intervention_date: '',           // 干预日期
      operator_name: '',               // 操作人员
      operator_relation: '',           // 与患者关系
      intervention_description: '',    // 干预描述
      daily_frequency: '',             // 每日频次
      child_cooperation: '',           // 孩子配合度
      daily_effect_rating: '',         // 每日效果评分
      parent_feedback: '',             // 家长反馈
      notes: ''                        // 备注
    },
    
    // 干预方式选项 - 从后端API获取
    interventionTypes: [],
    
    // 关系选项
    relationOptions: [
      { value: 'parent', label: '父母' },
      { value: 'grandparent', label: '祖父母' },
      { value: 'guardian', label: '监护人' },
      { value: 'other', label: '其他' }
    ],
    
    // 配合度选项
    cooperationOptions: [
      { value: 'excellent', label: '优秀' },
      { value: 'good', label: '良好' },
      { value: 'fair', label: '一般' },
      { value: 'poor', label: '较差' }
    ],
    
    // 效果评分选项
    effectRatingOptions: [
      { value: '1', label: '1分' },
      { value: '2', label: '2分' },
      { value: '3', label: '3分' },
      { value: '4', label: '4分' },
      { value: '5', label: '5分' }
    ],
    
    // 图片相关
    images: [],                        // 图片临时路径
    uploadedImages: [],                // 已上传的图片URL
    imageUploading: false,             // 图片上传状态
    
    // 表单状态
    submitting: false,                 // 提交状态
    formErrors: {},                    // 表单错误信息
    
    // 页面状态
    loading: false,
    error: null,
    
    // 选择器索引
    interventionTypeIndex: 0,
    relationIndex: 0,
    cooperationIndex: 0,
    effectRatingIndex: 0,
    
    // 选择器标签
    selectedInterventionTypeLabel: '',
    selectedRelationLabel: '',
    selectedCooperationLabel: '',
    selectedEffectRatingLabel: ''
  },

  /**
   * 页面加载时检查登录状态和加载配置
   */
  onLoad() {
    this.checkLoginStatus();
    this.loadInterventionConfig();
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const token = getToken();
    if (!token) {
      wx.showToast({ 
        title: '请先登录', 
        icon: 'none' 
      });
      setTimeout(() => {
        wx.navigateTo({ url: '/pages/index/index' });
      }, 1500);
      return;
    }
    
    // 设置默认日期为今天
    const today = new Date();
    const dateStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
    this.setData({
      'formData.intervention_date': dateStr
    });
  },

  /**
   * 加载干预配置
   */
  async loadInterventionConfig() {
    try {
      const token = getToken();
      if (!token) {
        console.log('未登录，跳过配置加载');
        return;
      }

      // 获取全局API基础地址
      const app = getApp();
      const apiBaseUrl = app.globalData.apiBaseUrl || 'https://vision.skyantkj.com/api/miniprogram';

      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${apiBaseUrl.replace('/miniprogram', '')}/config/intervention/records?scope=simple`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: resolve,
          fail: reject
        });
      });

      if (response.data && response.data.success) {
        const { intervention_types } = response.data.data;
        
        // 转换为小程序需要的格式
        const interventionTypes = intervention_types.map(type => ({
          value: type,
          label: type
        }));

        this.setData({
          interventionTypes
        });
        
        console.log('干预配置加载成功:', { intervention_types });
      } else {
        console.error('配置加载失败:', response.data);
        wx.showToast({
          title: '配置加载失败',
          icon: 'error'
        });
      }
    } catch (error) {
      console.error('配置加载异常:', error);
      wx.showToast({
        title: '配置加载失败',
        icon: 'error'
      });
    }
  },

  /**
   * 表单输入事件处理
   */
  onInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    this.setData({
      [`formData.${field}`]: value,
      [`formErrors.${field}`]: '' // 清除对应字段的错误
    });
  },

  /**
   * 选择图片
   */
  chooseImage() {
    wx.chooseImage({
      count: 9 - this.data.images.length, // 最多9张图片
      sizeType: ['compressed'], // 压缩图片
      sourceType: ['album', 'camera'],
      success: (res) => {
        const newImages = this.data.images.concat(res.tempFilePaths);
        this.setData({ images: newImages });
      },
      fail: (error) => {
        wx.showToast({ 
          title: '选择图片失败', 
          icon: 'none' 
        });
      }
    });
  },

  /**
   * 删除图片
   */
  deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.images.filter((_, i) => i !== index);
    this.setData({ images });
  },

  /**
   * 预览图片
   */
  previewImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.images;
    
    wx.previewImage({
      current: images[index],
      urls: images
    });
  },

  /**
   * 上传图片到服务器
   */
  async uploadImages() {
    if (this.data.images.length === 0) {
      return [];
    }

    this.setData({ imageUploading: true });
    const uploadedUrls = [];

    try {
      for (let i = 0; i < this.data.images.length; i++) {
        const imagePath = this.data.images[i];
        
        const uploadResult = await new Promise((resolve, reject) => {
          wx.uploadFile({
            url: `${getApp().globalData.apiBaseUrl}/intervention/upload_image`,
            filePath: imagePath,
            name: 'image',
            header: {
              'Authorization': `Bearer ${getToken()}`
            },
            success: (res) => {
              const data = JSON.parse(res.data);
              if (data.success) {
                resolve(data.data.image_url);
              } else {
                reject(new Error(data.message || '图片上传失败'));
              }
            },
            fail: (error) => {
              reject(new Error('图片上传失败：' + error.errMsg));
            }
          });
        });

        uploadedUrls.push(uploadResult);
      }
    } catch (error) {
      wx.showToast({ 
        title: error.message || '图片上传失败', 
        icon: 'none' 
      });
      throw error;
    } finally {
      this.setData({ imageUploading: false });
    }

    return uploadedUrls;
  },

  /**
   * 验证表单数据
   */
  validateForm() {
    const errors = {};
    const { formData } = this.data;

    // 必填字段验证
    if (!formData.intervention_type) {
      errors.intervention_type = '请选择干预方式';
    }
    
    if (!formData.intervention_date) {
      errors.intervention_date = '请选择干预日期';
    }
    
    if (!formData.operator_name) {
      errors.operator_name = '请输入操作人员姓名';
    }
    
    if (!formData.operator_relation) {
      errors.operator_relation = '请选择与患者关系';
    }
    
    if (!formData.daily_frequency) {
      errors.daily_frequency = '请输入每日频次';
    }
    
    if (!formData.child_cooperation) {
      errors.child_cooperation = '请选择孩子配合度';
    }
    
    if (!formData.daily_effect_rating) {
      errors.daily_effect_rating = '请选择每日效果评分';
    }

    this.setData({ formErrors: errors });
    return Object.keys(errors).length === 0;
  },

  /**
   * 提交表单
   */
  async submitForm() {
    if (!this.validateForm()) {
      wx.showToast({ 
        title: '请完善表单信息', 
        icon: 'none' 
      });
      return;
    }

    this.setData({ submitting: true });

    try {
      // 先上传图片
      const imageUrls = await this.uploadImages();
      
      // 准备提交数据
      const submitData = {
        intervention_date: this.data.formData.intervention_date,
        intervention_type: this.data.formData.intervention_type,
        operator_name: this.data.formData.operator_name,
        operator_relation: this.data.formData.operator_relation,
        daily_frequency: this.data.formData.daily_frequency,
        child_cooperation: this.data.formData.child_cooperation,
        daily_effect_rating: this.data.formData.daily_effect_rating,
        parent_feedback: this.data.formData.parent_feedback,
        notes: this.data.formData.notes,
        is_home_intervention: true,
        upload_source: 'miniprogram',
        image_urls: imageUrls
      };

      // 提交干预记录
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${getApp().globalData.apiBaseUrl}/intervention/home`,
          method: 'POST',
          header: {
            'Authorization': `Bearer ${getToken()}`,
            'Content-Type': 'application/json'
          },
          data: submitData,
          success: resolve,
          fail: reject
        });
      });

      if (response.data.success) {
        wx.showToast({ 
          title: '提交成功', 
          icon: 'success' 
        });
        
        // 重置表单
        this.resetForm();
        
        // 返回上一页或跳转到查询页面
        setTimeout(() => {
          wx.navigateTo({ url: '/pages/query/query' });
        }, 1500);
      } else {
        throw new Error(response.data.message || '提交失败');
      }
    } catch (error) {
      wx.showToast({ 
        title: error.message || '提交失败', 
        icon: 'none' 
      });
    } finally {
      this.setData({ submitting: false });
    }
  },

  /**
   * 重置表单
   */
  resetForm() {
    const today = new Date();
    const dateStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
    
    this.setData({
      formData: {
        intervention_type: '',
        intervention_date: dateStr,
        operator_name: '',
        operator_relation: '',
        intervention_description: '',
        daily_frequency: '',
        child_cooperation: '',
        daily_effect_rating: '',
        parent_feedback: '',
        notes: ''
      },
      images: [],
      uploadedImages: [],
      formErrors: {},
      // 重置选择器索引和标签
      interventionTypeIndex: 0,
      relationIndex: 0,
      cooperationIndex: 0,
      effectRatingIndex: 0,
      selectedInterventionTypeLabel: '',
      selectedRelationLabel: '',
      selectedCooperationLabel: '',
      selectedEffectRatingLabel: ''
    });
  },

  /**
   * 选择日期
   */
  onDateChange(e) {
    this.setData({
      'formData.intervention_date': e.detail.value,
      'formErrors.intervention_date': ''
    });
  },

  /**
   * 选择干预方式
   */
  onInterventionTypeChange(e) {
    const index = e.detail.value;
    const selectedType = this.data.interventionTypes[index];
    this.setData({
      'formData.intervention_type': selectedType.value,
      'interventionTypeIndex': index,
      'selectedInterventionTypeLabel': selectedType.label,
      'formErrors.intervention_type': ''
    });
  },

  /**
   * 选择关系
   */
  onRelationChange(e) {
    const index = e.detail.value;
    const selectedRelation = this.data.relationOptions[index];
    this.setData({
      'formData.operator_relation': selectedRelation.value,
      'relationIndex': index,
      'selectedRelationLabel': selectedRelation.label,
      'formErrors.operator_relation': ''
    });
  },

  /**
   * 选择配合度
   */
  onCooperationChange(e) {
    const index = e.detail.value;
    const selectedCooperation = this.data.cooperationOptions[index];
    this.setData({
      'formData.child_cooperation': selectedCooperation.value,
      'cooperationIndex': index,
      'selectedCooperationLabel': selectedCooperation.label,
      'formErrors.child_cooperation': ''
    });
  },

  /**
   * 选择效果评分
   */
  onEffectRatingChange(e) {
    const index = e.detail.value;
    const selectedRating = this.data.effectRatingOptions[index];
    this.setData({
      'formData.daily_effect_rating': selectedRating.value,
      'effectRatingIndex': index,
      'selectedEffectRatingLabel': selectedRating.label,
      'formErrors.daily_effect_rating': ''
    });
  }
});